package com.littlebee.storysuper.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Handler;
import android.os.Parcelable;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.czt.mp3recorder.MP3Recorder;
import com.littlebee.storysuper.R;
import com.littlebee.storysuper.common.sharePrefUtils.SharePrefUtil;
import com.littlebee.storysuper.entry.Audiolist;
import com.littlebee.storysuper.entry.BabyStoryPlanEntry;
import com.littlebee.storysuper.entry.MyStoryEntry;
import com.littlebee.storysuper.entry.Playinfo;
import com.littlebee.storysuper.entry.StorySeriesEntry;
import com.littlebee.storysuper.entry.User;
import com.littlebee.storysuper.tcp.SendCmdBean;
import com.littlebee.storysuper.tcp.TcpClientUtil;
import com.littlebee.storysuper.utils.Constant;
import com.littlebee.storysuper.utils.DateUtils;
import com.littlebee.storysuper.utils.GlideImageLoader;
import com.littlebee.storysuper.utils.GsonUtils;
import com.littlebee.storysuper.utils.LogUtil;
import com.littlebee.storysuper.utils.NetWorkUtils;
import com.littlebee.storysuper.utils.ToastUtil;
import com.littlebee.storysuper.utils.Utils;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.zss.library.PermissionCallBack;
import com.zss.library.activity.BaseActivity;
import com.zss.library.adapter.CommonAdapter;
import com.zss.library.adapter.ViewHolder;
import com.zss.library.toolbar.CommonToolbar;
import com.zss.library.utils.FileUtils;
import com.zss.library.utils.LogUtils;
import com.zss.library.utils.SharedPrefUtils;
import com.zss.library.widget.CommonWhiteDialog;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import static com.littlebee.storysuper.common.sharePrefUtils.SharePrefUtil.kCallingStatus;

/**
 * 故事详情
 */
public class StoryInfoActivity extends BaseActivity implements ViewPager.OnPageChangeListener, View.OnClickListener {


    Banner banner;
    private ListView gridView;
    MyStoryEntry myStoryEntry;
    List<String> urls = new ArrayList<String>();
    List<String> titles = new ArrayList<String>();
    private CommonAdapter<Audiolist> mAdapter;
    List<Audiolist> audiolists = new ArrayList<Audiolist>();
    private StorySeriesEntry babyStoryPlanEntry = new StorySeriesEntry();
    private BabyStoryPlanEntry babyStoryPlanEntry1 = new BabyStoryPlanEntry();

    private String fileName;
    private boolean isStopCount = false;
    private long timer = 0;
    private Handler mHandler = new Handler();
    private TextView toRec;
    private TextView lestionTv, sendTv;
    private TextView syncTv;
    private LinearLayout lyBtm;
    private LinearLayout ll_sync;
    private LinearLayout ll_record;

    /**
     * 是否在录制 0 没有录制 1 录制中 2 录制完毕
     */
    private int isRec = 0;
    List<Playinfo> infos = new ArrayList<Playinfo>();
    private int defIndex = 0;

    SharedPreferences sharedPreferences;
    private boolean isPlan;
    ImageView volume;

    @Override
    public int getLayoutResId() {
        return R.layout.activity_story1_info;
    }

    @Override
    public void initView() {
        super.initView();
        sharedPreferences = getSharedPreferences(Constant.appName, Context.MODE_PRIVATE); //私有数据

        banner = (Banner) findViewById(R.id.banner);
        banner.setRightScrollDisable(true);

        gridView = (ListView) findViewById(R.id.listView);

        toRec = (TextView) findViewById(R.id.to_rac);
        lestionTv = (TextView) findViewById(R.id.to_lestion);
        sendTv = (TextView) findViewById(R.id.to_send);
        lyBtm = (LinearLayout) findViewById(R.id.ly_btm);
        banner.setOnPageChangeListener(this);
        toRec.setOnClickListener(this);
        lestionTv.setOnClickListener(this);
        sendTv.setOnClickListener(this);
        volume = (ImageView) findViewById(R.id.show_rec_fy);

        syncTv = (TextView) findViewById(R.id.to_sync);
        syncTv.setOnClickListener(this);
        ll_sync = (LinearLayout) findViewById(R.id.ll_sync);
        ll_record = (LinearLayout) findViewById(R.id.ll_record);

        addCallingView();
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        mAdapter = new CommonAdapter<Audiolist>(getActivity(), R.layout.layout_item_story_info) {
            @Override
            protected void convert(ViewHolder viewHolder, Audiolist workerListEntry, int i) {
                TextView name = viewHolder.findViewById(R.id.tv);
                TextView name1 = viewHolder.findViewById(R.id.tv_1);
                name.setText(workerListEntry.getCaptiontxt());
                name1.setText((i + 1) + "");

            }
        };
        gridView.setAdapter(mAdapter);
        mAdapter.addAll(audiolists);
        if (getIntent().getBooleanExtra("isInfo", false) == false) {
            if (getIntent().getBooleanExtra("isPlan", false) == false) {
                babyStoryPlanEntry = (StorySeriesEntry) getIntent().getSerializableExtra("info");
            } else {
                babyStoryPlanEntry1 = (BabyStoryPlanEntry) getIntent().getSerializableExtra("info");
            }
            getStoryInfo();
        } else {
            myStoryEntry = (MyStoryEntry) getIntent().getSerializableExtra("info");
            for (int i = 0; i < myStoryEntry.getStorypages().size(); i++) {
                infos.add(new Playinfo(Integer.parseInt(myStoryEntry.getStorypages().get(i).getPageno().trim()), 0, 0));
                urls.add(myStoryEntry.getStorypages().get(i).getPageurl());
                titles.add("滑动图片，故事翻页");
            }

            //默认是CIRCLE_INDICATOR
            banner.setImages(urls)
                    .setBannerTitles(titles)
                    .setBannerStyle(BannerConfig.NUM_INDICATOR_TITLE)
                    .setImageLoader(new GlideImageLoader())
                    .start();

            RushList(0);
        }
    }

    private void addCallingView() {
        LinearLayout callingLayout = (LinearLayout) findViewById(R.id.ll_calling);
        callingLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int status = SharePrefUtil.getInstance(StoryInfoActivity.this).getIntValue(kCallingStatus);
                if (status == 3) {
                    ToastUtil.displayLongToast("您在录制过程中，不能进入实时通话。。。");
                    return;
                }
                startActivity(new Intent(StoryInfoActivity.this, VoiceCallingActivity.class));
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (TcpClientUtil.getInstance().isTcpConnect()) {
            ll_sync.setVisibility(View.VISIBLE);
            ll_record.setVisibility(View.GONE);
        } else {
            ll_sync.setVisibility(View.GONE);
            ll_record.setVisibility(View.VISIBLE);
        }
    }

    /*
        * 拉取故事
        *
        * */
    public void getStoryInfo() {
        //phoneId=18611697983&storyid=1
        Map<String, String> hashMap = new HashMap<>();
        User user = Utils.getUserEntry();
        hashMap.put("phoneId", user.getMobile());
        if (getIntent().getBooleanExtra("isPlan", false) == false) {
            hashMap.put("storyid", babyStoryPlanEntry.getStoryseriesid());
        } else {
            hashMap.put("storyid", babyStoryPlanEntry1.getStoryid());
        }
        NetWorkUtils.post(getActivity(), "getstoryinfo", hashMap, true, new NetWorkUtils.IListener() {

            @Override
            public void onSuccess(String result, JSONObject resObj) {
                String res = resObj.optString("response")/**.optString("storypages")*/;
                myStoryEntry = GsonUtils.getObjFromJSON(res, MyStoryEntry.class);
                for (int i = 0; i < myStoryEntry.getStorypages().size(); i++) {
                    infos.add(new Playinfo(Integer.parseInt(myStoryEntry.getStorypages().get(i).getPageno().trim()), 0, 0));
                    urls.add(myStoryEntry.getStorypages().get(i).getPageurl());
                    titles.add("滑动图片，故事翻页");
                }

                //默认是CIRCLE_INDICATOR
                banner.setImages(urls)
                        .setBannerTitles(titles)
                        .setBannerStyle(BannerConfig.NUM_INDICATOR_TITLE)
                        .setImageLoader(new GlideImageLoader())
                        .start();

                RushList(0);

            }

            @Override
            public void onError(String result, String code, String msg) {
                LogUtils.i("XHX", "XHXERROR:" + result);


            }
        });
    }

    /*
     * 发送录音故事
     *
     * */
    public void sendStoryInfo(String path) {
        Map<String, String> hashMap = new HashMap<>();
        User user = Utils.getUserEntry();
        hashMap.put("phoneId", user.getMobile());
        hashMap.put("storyid", myStoryEntry.getStoryid());
        hashMap.put("recordaudioname", user.getMobile() + "-" + DateUtils.getTimeDayNull(System.currentTimeMillis()) + ".mp3");
        hashMap.put("audiomsgurl", path);
        hashMap.put("recordaudiodownurl", path);
        JSONArray jsonArray = new JSONArray();
        JSONObject tmpObj = null;
        for (int i = 0; i < infos.size(); i++) {
            tmpObj = new JSONObject();
            try {
                tmpObj.put("pageno", infos.get(i).getPageno());
                tmpObj.put("startsecond", infos.get(i).getStartsecond());
                tmpObj.put("endsecond", infos.get(i).getEndsecond());
                jsonArray.put(tmpObj);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            tmpObj = null;
        }
        hashMap.put("playinfos", jsonArray.toString());
        LogUtils.i("XHX", "获取到的下标：" + jsonArray.toString());
        NetWorkUtils.post(getActivity(), "setstoryrecord", hashMap, true, new NetWorkUtils.IListener() {

            @Override
            public void onSuccess(String result, JSONObject resObj) {
                ToastUtil.displayShortToast("上传故事成功");
                finish();
            }

            @Override
            public void onError(String result, String code, String msg) {
                LogUtils.i("XHX", "XHXERROR:" + result);
                ToastUtil.displayShortToast("上传故事失败");
            }
        });


    }

    /*
      * 上传录音文件
      *
      * */
    public void uploadStoryInfo() {
        NetWorkUtils.upload(getActivity(), Constant.UPLOAD_PATH, new File(fileName), new NetWorkUtils.IProgressListener() {

            @Override
            public void onSuccess(String result, JSONObject resObj) {
                LogUtils.i("XHX", "ACTIVITY接受到了：" + result.toString());
                try {
                    String res = resObj.getJSONObject("response").optString("url");
                    sendStoryInfo(res);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onProgress(int index, long totalBytes, long surplusBytes, boolean done) {
                LogUtils.i("XHX", "进度：" + surplusBytes + ";总进度：" + totalBytes);
            }

            @Override
            public void onError(String result, String code, String msg) {
                LogUtils.i("XHX", "ACTIVITY接受到了失败：" + result.toString());
                ToastUtil.displayShortToast("上传故事失败");

            }
        });

    }

    @Override
    public void setTopBar() {
        super.setTopBar();
        setStatusBarColor(R.color.module_video_bg);
        CommonToolbar toolbar = getToolbar();
        toolbar.setBgRes(R.color.trans);
        if (getIntent().getBooleanExtra("isInfo", false) == false) {
            if (getIntent().getBooleanExtra("isPlan", false) == false) {
                toolbar.setTitle(babyStoryPlanEntry.getStoryseriesname());
                //toolbar.setTitle("");

            } else {
                toolbar.setTitle(babyStoryPlanEntry1.getStoryname());
                //toolbar.setTitle("");

            }
        } else {
            toolbar.setTitle(myStoryEntry.getStoryname());
            //toolbar.setTitle("");


        }

    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        if (position < 0) {
        } else {
            if (position == myStoryEntry.getStorypages().size()) {
                banner.setViewPagerIsScroll(false);
            }
            LogUtils.i("XHX", "XHX下表L:" + (position));
            RushList(position - 1);
        }

    }

    private void RushList(int index) {
        defIndex = index;
        LogUtils.i("XHX", "XHX下表LLLL:" + (index));
        if (myStoryEntry != null && myStoryEntry.getStorypages() != null && myStoryEntry.getStorypages().size() > index) {
            if (index >=0 ) {
                audiolists = myStoryEntry.getStorypages().get(index).getPagecaptionns();
                LogUtils.i("XHX", "XHXSIe:" + audiolists.size());
                mAdapter.replaceAll(audiolists);
                syncPage(index);
            }
        }
        if (isRec == 1) {
            if (index > 0) {

                changeItem(index - 1, false, timer);
                changeItem(index, true, timer);

            }
        }
    }

    private void syncPage(int index) {
        TcpClientUtil.getInstance().sendMessage(myStoryEntry.getStoryid(), index);
        ToastUtil.displayShortToast("指令发送成功...");
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    protected void onPause() {
        super.onPause();
        mediaRelease();

    }
    //******************* 录音 ************************

    private MediaPlayer mPlayer = null;
    private MP3Recorder mRecorder = null;

    //开始录音
    public void startRecording() {
        SharePrefUtil.getInstance(this).setObject(kCallingStatus, 3);
        verifyPermissions(getActivity(), Manifest.permission.RECORD_AUDIO,
                new String[]{Manifest.permission.RECORD_AUDIO, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}
                , 0x01, new PermissionCallBack() {

                    @Override
                    public void onGranted() {
                        File file = new File(FileUtils.getExtDir(getActivity()) + Constant.appName);
                        if (!file.exists()) {
                            file.mkdir();
                        }
                        boolean highQuality = true;
                        User user = Utils.getUserEntry();
                        fileName = file.getPath() + File.separator + user.getMobile() + "-" + DateUtils.getTimeDayNull(System.currentTimeMillis()) + ".mp3";


                        //开始录音
                        mRecorder = new MP3Recorder(new File(fileName));
                        try {
                            mRecorder.start();
                        } catch (IOException e) {
                            e.printStackTrace();
                            LogUtil.e("prepare() failed");
                        }
                    }

                    @Override
                    public void onDenied() {
                    }
                });
    }

    /**
     * 停止录音
     */
    private void stopRecording() {
        SharePrefUtil.getInstance(this).setObject(kCallingStatus, 1);
        if (mRecorder != null) {
            //停止录音
            mRecorder.stop();
            mRecorder = null;
        } else {
            ToastUtil.displayShortToast("还未开始录制");
        }
    }

    private void startPlayer(String item) {
        mPlayer = new MediaPlayer();
        lestionTv.setText("试听中……");
        mPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            public boolean onError(MediaPlayer mp, int what, int extra) {
                mediaRelease();
                return true;
            }
        });
        mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                mediaRelease();
                lestionTv.setText("试 听");

            }
        });
        try {
            mPlayer.setDataSource(item);
            final AudioManager audioManager = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);
            if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
                mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
                mPlayer.setLooping(false);
                mPlayer.prepare();
                mPlayer.start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 得到amr的时长
     *
     * @param file
     * @return amr文件时间长度
     * @throws IOException
     */
    public static int getAmrDuration(String file) throws IOException {
        int leng = 0;
        MediaPlayer player = new MediaPlayer();
        player.setDataSource(file);
        player.prepare();
        leng = player.getDuration();
        player.release();
        player = null;
        return leng;
    }

    private void mediaRelease() {
        if (mPlayer != null) {
            mPlayer.release();
            mPlayer = null;
        }
    }

    private Runnable TimerRunnable = new Runnable() {

        @Override
        public void run() {
            if (!isStopCount) {
                timer += 300;
                // TODO: 2017/8/28
                toRec.setText("录制中（" + DateUtils.getTimeString(timer) + "）……");
                updateDisplay(new Random().nextInt(13));
            }
            countTimer();
        }
    };

    private void countTimer() {
        mHandler.postDelayed(TimerRunnable, 300);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.to_sync:
                if (TcpClientUtil.getInstance().isTcpConnect()) {
                    ToastUtil.displayLongToast("翻动图片，会同步给宝宝");
                    syncTv.setText("同步中...");
                    TcpClientUtil.getInstance().setTcpSync(true);
                } else {
                    TcpClientUtil.getInstance().setTcpSync(false);
                    ToastUtil.displayLongToast("请先通过实时通话呼叫宝宝...");
                }
                break;
            case R.id.to_rac:
                if (isRec == 0) {
                    if (sharedPreferences.getBoolean("isConfig", false) == true) {
                        initToPlayer();
                    } else {
                        final CommonWhiteDialog dialog = new CommonWhiteDialog(this);
                        dialog.setTitle("提 醒");
                        dialog.setContentText("使用耳机创作，效果更佳");
                        dialog.setDisplayMiddleEnable(true);
                        dialog.setOnClickCancelListener("确 定", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                initToPlayer();
                                dialog.dismiss();
                            }
                        });
                        dialog.setOnClickConfirmListener("不再提醒", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                sharedPreferences.edit().putBoolean("isConfig", true).commit();
                                initToPlayer();
                                dialog.dismiss();

                            }
                        });
                        dialog.show();
                    }
                } else if (isRec == 1) {
                    isStopCount = true;
                    isRec = 2;
                    toRec.setText("重 录");
                    volume.setVisibility(View.GONE);
                    stopRecording();
                    try {
                        changeItem(defIndex, false, getAmrDuration(fileName));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    lyBtm.setVisibility(View.VISIBLE);
                } else {
                    initFirst();
                }
                break;
            case R.id.to_lestion:
                //试听
                Intent intent = new Intent(StoryInfoActivity.this, PlayerStoryInfoActivity.class);
                intent.putExtra("info", myStoryEntry);
                intent.putParcelableArrayListExtra("time", (ArrayList<? extends Parcelable>) infos);
                intent.putExtra("url", fileName);
                startActivity(intent);
                break;
            case R.id.to_send:
                isRec = 0;
                toSend();
                break;
        }
    }

    private void initToPlayer() {
        timer = 0;
        if (TimerRunnable != null) {
            mHandler.removeCallbacks(TimerRunnable);
        }
        countTimer();
        isStopCount = false;
        isRec = 1;
        changeItem(0, true, 0);
        volume.setVisibility(View.VISIBLE);

        startRecording();
    }

    private void initFirst() {
        lyBtm.setVisibility(View.GONE);
        timer = 0;
        isRec = 0;
        infos.clear();

        //默认是CIRCLE_INDICATOR
        banner.setImages(urls)
                .setBannerTitles(titles)
                .setBannerStyle(BannerConfig.NUM_INDICATOR_TITLE)
                .setImageLoader(new GlideImageLoader())
                .start();
        banner.setViewPagerIsScrollUI(true);

        RushList(0);
        for (int i = 0; i < myStoryEntry.getStorypages().size(); i++) {
            infos.add(new Playinfo(Integer.parseInt(myStoryEntry.getStorypages().get(i).getPageno().trim()), 0, 0));
        }
        toRec.setText("开始录制");
    }

    private void changeItem(int i, boolean isStart, long time) {
        //修改为ms作为时间单位
        if (infos != null && infos.size() > 0) {
            if (isStart) {
                infos.get(i).setStartsecond(time);
            } else {
                infos.get(i).setEndsecond(time);
            }
        }

    }

    private void toSend() {
        uploadStoryInfo();
    }

    private void updateDisplay(int signalEMA) {

        switch ((int) signalEMA) {
            case 0:
            case 1:
                volume.setImageResource(R.drawable.ease_record_animate_02);
                break;
            case 2:
            case 3:
                volume.setImageResource(R.drawable.ease_record_animate_04);

                break;
            case 4:
            case 5:
                volume.setImageResource(R.drawable.ease_record_animate_07);
                break;
            case 6:
            case 7:
                volume.setImageResource(R.drawable.ease_record_animate_09);
                break;
            case 8:
            case 9:
                volume.setImageResource(R.drawable.ease_record_animate_11);
                break;
            case 10:
            case 11:
                volume.setImageResource(R.drawable.ease_record_animate_13);
                break;
            default:
                volume.setImageResource(R.drawable.ease_record_animate_14);
                break;
        }
    }

}
